<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>豆瓣-登录注册</title>
    <link rel="stylesheet" href="/css/sign.css">

</head>

<body>
<div>
    <div class="back">
        <svg width="15px" height="15px" viewBox="0 0 16 16" class="bi bi-chevron-left" fill="currentColor"
             xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd"
                  d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
        </svg>
        <a href="/index">返回</a>
    </div>

    <div class="login-register">
        <div class="wapper">
            <div class="switch" id="switch">
                <button>密码登录</button>
                <button>扫码登录</button>
                <button>注册</button>
            </div>
            <ul class="box" id="box">
                <li class="show">
                    <div class="form">
                        <div style="display: none" class="login-error">
                            <svg width="11px" height="11px" viewBox="0 0 16 16" class="bi bi-dash-circle"
                                 fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                <path fill-rule="evenodd"
                                      d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                <path fill-rule="evenodd"
                                      d="M3.5 8a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.5-.5z"/>
                            </svg>
                            <span class="pwd-err">账号密码错误</span>
                        </div>
                        <div>
                            <input type="text" id="login-name" name="name" placeholder="请输入用户名">
                        </div>
                        <div>
                            <input type="password" id="login-pwd" name="password" placeholder="请输入密码">
                        </div>

                        <div>
                            <button class="b-login">登录豆瓣</button>
                        </div>
                        <div class="checkbox">
                            <input class="checkbox" type="checkbox">
                            <span> 下次自动登录</span>
                        </div>

                    </div>
                </li>
                <li class="qrcode">
                    <div class="qrCodeImg-box" id="qrImgDiv"></div>
                </li>
                <li class="regi">
                    <div class="form">
                        <div>
                            <input type="text" id="reg-name" name="name" placeholder="请输入用户名">
                        </div>
                        <div>
                            <input type="password" id="reg-pwd" name="password" placeholder="请输入密码">
                        </div>
                        <div>
                            <input type="password" id="reg-dpwd" placeholder="确认密码">
                        </div>
                        <div>
                            <input type="password" id="reg-mobile" name="mobile" placeholder="手机号">
                        </div>
                        <div>
                            <button id="regi-btn" type="submit">注册豆瓣</button>
                        </div>
                        <div>
                </li>

            </ul>
        </div>
    </div>
</div>
</body>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    //注册登录窗口切换
    let buttonList = document.getElementById("switch").children;
    let box = document.getElementById("box").children;
    for (let index = 0; index < buttonList.length; index++) {
        buttonList[index].addEventListener("click", function () {
            // if(box[i].className!=="show"){
            //     box[i].className = "show";
            // }else{
            //     box[i].className = "regi";
            // }
          /*  if (index ===1){
                console.log(index)
                initQrImg()
            }*/
            for (let i = 0; i < buttonList.length; i++) {
                buttonList[i].removeAttribute("class");
                box[i].removeAttribute('class');
            }
            this.className = "current-button";
            box[index].className = "show";
        });

    }

    //表单不为空提示
    function validatedNull(e) {
        let value = e.target.value;
        if (value.trim() === null || value.trim() === "") {
            e.target.style.borderColor = "red";
        } else {
            e.target.style.borderColor = "#E2E2E2";
        }
    }

    let inputdom = document.querySelectorAll("input");
    //事件监听
    inputdom.forEach(element => {
        element.addEventListener('blur', validatedNull);
    });
    let path = "://localhost:8080";
    let getQrPath =  "http" + path + "/app/getLoginQr";
    let wsPath =     "ws" + path + "/websocket/";
    //初始化二维码
    function initQrImg() {
        $("#qrImgDiv").empty();
        var xmlhttp;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", getQrPath, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
            console.log(this);
            uuid = this.getResponseHeader("uuid");
            console.log(uuid)

            if (this.status == 200) {
                var blob = this.response;
                console.log(blob)
                var img = document.createElement("img");
                img.className = 'qrCodeBox-img';
                img.onload = function (e) {
                    window.URL.revokeObjectURL(img.src);
                };
                img.src = window.URL.createObjectURL(blob);
                document.getElementById("qrImgDiv").appendChild(img);
                console.log(img)
                initWebSocket();
            }
        }
        xmlhttp.send();
    }
     //开启websocket
    function initWebSocket(){

        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
            var wsPathStr = wsPath+uuid;
            socket = new WebSocket(wsPathStr);
            //打开事件
            socket.onopen = function() {
                console.log("Socket 已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                // var data = JSON.parse(msg.data);
                if(msg.data == "success"){
                    alert("登录成功！");
                    //这里存放自己业务需要的数据。怎么放自己看
                    // window.sessionStorage.uuid = uuid;
                    // window.sessionStorage.userId = data.userId;
                    // window.sessionStorage.projId = data.projId;

                    window.location.href = "https://www.baidu.com"
                }else{
                    //如果过期了，关闭连接、重置连接、刷新二维码
                    socket.close();
                    initQrImg();
                }
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function() {
                console.log("Socket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                alert("Socket发生了错误");
                //此时可以尝试刷新页面
            }
        }

    }

    //登录与注册
    $(document).ready(function () {
         initQrImg()
        $(".b-login").click(() => {
            let name = $("#login-name").val();
            let pwd = $("#login-pwd").val();

            if (!name || name === '' || !pwd || pwd === "") {
                alert("账号密码不能为空！");
                return;
            }

            $.post("http://localhost:8080/app/authenticate",
                {
                    name: name,
                    password: pwd
                },
                function (data, status) {
                    if (status) {
                        if (data.result) {
                            window.location.href = "/index";
                        } else {
                            $(".login-error").show();
                        }
                    }

                });
        });

        /**
         * 注册
         */

        $("#regi-btn").click(() => {
            let name = $("#reg-name").val();
            let pwd = $("#reg-pwd").val();
            let dpwd = $("#reg-dpwd").val();
            let mobile = $("#reg-mobile").val();
            if (!name || name === "" || !pwd || pwd === "" || !dpwd || dpwd === "" || !mobile || mobile.trim() === "") {
                alert("检查表单完整性");
                return;
            }
            if (pwd !== dpwd) {
                alert("两次密码不一致哦");
                return;
            }

            $.post("http://localhost:8080/app/register",
                {
                    name: name,
                    password: pwd,
                    mobile: mobile
                },
                function (data, status) {
                    if (status) {
                        if (data.result) {
                            alert("注册成功")
                        } else {
                            alert("注册失败：" + data.message);
                        }
                    }

                });

        })
    });

</script>

</html>